<!--
*@Author: QWP
*@Description: 整个流程属性
*@Date 2024-08-14 10:29
-->
<template>
  <div class="app-container">
    <u-form :model="ruleForm"
      :elements="formEls">
    </u-form>
    <div class="theme-main-container" v-if="1 == 2">
      <!-- 搜索 -->
      <div class="filter-container">
        <a-tabs v-model:value="subActiveName" type="card">
          <a-tab-pane tab="参数设置" key="1">
            <a-space>
              <u-icon-button itype="add" type="success" size="mini" @click="addtable" >
                添加
              </u-icon-button>
              <u-icon-button itype="close" size="mini" @click="qingchutable" >
                清空
              </u-icon-button>
              <u-icon-button itype="delete" size="mini" @click="deltable" >
                删除
              </u-icon-button>
            </a-space>
            <u-edit-table :data="proceParams"
              :columns="paramsCols"
              :addBtn="false"
              :deleteBtn="false"
              ref="proceParamsTable"
              @onSelect="handleDetailSelectionChange">
            </u-edit-table>
          </a-tab-pane>
          <a-tab-pane tab="逾期设置" key="2">
            <u-form :model="ruleOverDue"
              :elements="outTimeEls">
            </u-form>
          </a-tab-pane>
          <a-tab-pane tab="定时启动" key="3">
            <u-form :model="timedStart"
              :elements="soldTimeEls">
              <template #remark>
                <span style="color: darkorange">{"TstWay":"MM(每月) or WK(每周) or DD(每天)","Remarks":"每月几号或每周几，每天为0","Timed":[{"hh":"8:30"},{"hh":"10:30"}]}</span>
              </template>
              <template #sqlStyle>
                <a-tag size="success">select username from sys_user</a-tag>
              </template>
            </u-form>
          </a-tab-pane>
          <a-tab-pane tab="事件管理" key="4">
            <u-edit-table :data="eventClass"
              :columns="eventCols"
              :addBtn="false"
              :deleteBtn="false"
              ref="eventClassParamsTable">
            </u-edit-table>
            <a-row>
              <div class="f-padding-r6">执行说明:</div>
              <a-col flex="1">
                <span style="color: darkorange">接口调用方式为POST，参数格式为{"processKey":"流程Key","task_def_key":"节点编号","proce_inst_id":"流程实例ID","businessKey":"业务数据主表id","others":{表单数据JSON}}</span>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
defineOptions({ name: 'ProcessProperties' })
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import { useTaskRuleStore, useProcessEventStore, useProcessParamsStore, useBaseStore  } from '@/store'
import { messageC, alertC } from '@/util/common'
import { _IFormEl, _IExtra } from '@/src/components/common/form/interface';
import { FormInstance, FormItemProps } from 'ant-design-vue';
import { processProperties } from '@bs/process/flowdesign.js'
import * as dynamiFormApi from '@/service/emergency/dynamicForms'

const props = defineProps({
  processId: '',
  deployMName:'',
  deploymentId:'',
  bpmElement: Object,
  properties: Object
})

const { modAndbill } = storeToRefs(useBaseStore())
const { eventTypes, eventWays } = storeToRefs(useProcessEventStore())
const { paramTypes, paramValueTypes, overDueWarnings, overDueWays, timedStartWays } = storeToRefs(useProcessParamsStore())

//流程分类
const sortdata = ref([])
//基本信息
const ruleForm = reactive({
  id: '',
  name: '',
  key:'',
  titleModel:'',
  sortid: '',
  process_key:''
})
const formItemProps: FormItemProps & _IExtra = {
  labelWidth: '90px',
  colon: false
}
// 基本信息的表单
const noLinkData = ref([])
const formEls: Array<_IFormEl> = reactive([
  { label: '流程Key', key: 'key', col: { span: 12,}, element: 'input', 
    formItemProps: { ...formItemProps, }, 
    componentProps: { disabled: true }, 
  },
  { label: '流程名称', key: 'name', col: { span: 12 }, element: 'input', 
    formItemProps: { ...formItemProps, }, 
    componentProps: { 
      onChange: (e) => {
        updateBaseInfo('name', e.target.value)
      }
    },
  },
  { label: '业务类型', key: 'billtype1', col: { span: 12 }, element: 'select', 
    formItemProps: { ...formItemProps, required: true },
    componentProps: { 
      fieldNames: { label: 'label', value: 'id' },
      options: modAndbill.value,
      onChange: (value, option) => {
        let datas = option.id.split('_BIZ_TYPE_')
        ruleForm.billmajortype = datas[0]
        ruleForm.billtype = datas[1]
        // 不是动态表单
        if(value != 'DYC_BIZ_TYPE_1') {
          ruleForm.fkdycform = ''
        }
      }
    },
  },
  { label: '动态业务', key: 'fkdycform', col: { span: 12 }, element: 'select', 
    formItemProps: { ...formItemProps, required: true },
    componentProps: { 
      disabled: computed(() => ruleForm.billtype1 != 'DYC_BIZ_TYPE_1'),
      fieldNames: { label: 'modulename', value: 'keyid' },
      options: computed(() => noLinkData.value),
    },
  }
])

//tabs标签
const subActiveName = ref('1')
//参数集合
const proceParams = ref([])
//选中的参数集合
const proceCheckedDetail = ref([])
//逾期信息
const ruleOverDue = ref({
  actionCycle:'',
  beforeTime:'',
  overDueWar:'0',
  overDueWarUrl:'',
  overDueWay:'0',
  overDueWayUrl:''
})
// 逾期信息的表单
const outTimeEls: Array<_IFormEl> = reactive([
  { label: '生命周期(D)', key: 'actionCycle', col: { span: 12,}, element: 'number', 
    formItemProps: { ...formItemProps, }, 
    componentProps: { precision: 0, min: 0 }, 
  },
  { label: '预警时间(H)', key: 'beforeTime', col: { span: 12,}, element: 'number', 
    formItemProps: { ...formItemProps, }, 
    componentProps: { precision: 0, min: 0 }, 
  },
  { label: '逾期预警', key: 'overDueWar', col: { span: 12 }, element: 'select', 
    formItemProps: { ...formItemProps, }, 
    componentProps: { 
      options: overDueWarnings.value, 
      onChange: (value) => {
        if(value != 2) {
          ruleOverDue.value.overDueWarUrl = ""
        }
      }
    },
  },
  { label: '预警接口', key: 'overDueWarUrl', element: 'input', 
    col: { span: computed(() => ruleOverDue.value.overDueWar == '2' ? 12 : 0) }, 
    formItemProps: { ...formItemProps, }, 
  },
  { label: '逾期处理', key: 'overDueWay', col: { span: 12 }, element: 'select', 
    formItemProps: { ...formItemProps, required: true },
    componentProps: { 
      options: overDueWays.value, 
      onChange: (value, option) => {
        if(value != 3) {
          ruleOverDue.value.overDueWayUrl = ""
        }
      }
    },
  },
  { label: '逾期接口', key: 'overDueWayUrl', element: 'input',
    col: { span: computed(() => ruleOverDue.value.overDueWay == '3' ? 12 : 0) }, 
    formItemProps: { ...formItemProps, }, 
  },
])
//定时启动
const timedStart = ref({
  tstWay:'0',
  tstDoc:'',
  userSql:''
})
// 定时启动的表单
const soldTimeEls: Array<_IFormEl> = reactive([
  { label: '启动设置', key: 'tstWay', col: { span: 12 }, element: 'select', 
    formItemProps: { ...formItemProps, }, 
    componentProps: { 
      options: timedStartWays.value, 
      onChange: (value) => {
        if(value != 1) {
          timedStart.value.tstDoc == ''
          timedStart.value.userSql == ''
        }
      }
    },
  },
  { label: '参数说明', key: 'remark', element: 'slot', 
    col: { span: computed(() => timedStart.value.tstWay == 1 ? 12 : 0) }, 
    formItemProps: { ...formItemProps, }, 
  },
  { label: '启动参数', key: 'tstDoc', element: 'input', 
    col: { span: computed(() => timedStart.value.tstWay == 1 ? 12 : 0) }, 
    formItemProps: { ...formItemProps, }, 
  },
  { label: '接收人员sql', key: 'userSql', element: 'input', 
    col: { span: computed(() => timedStart.value.tstWay == 1 ? 12 : 0) }, 
    formItemProps: { ...formItemProps, }, 
  },
  { label: 'sql格式', key: 'sqlStyle', element: 'slot', 
    col: { span: computed(() => timedStart.value.tstWay == 1 ? 12 : 0) }, 
    formItemProps: { ...formItemProps, }, 
  },
])
//事件
const eventClass = ref([])
const eventCols = [
  { dataIndex: "index", title: "序号", width: 80, align: 'center',  },
  { dataIndex: "eventType", title: "事件类型", minWidth: 100, align: 'center',  element: 'select',
    componentProps: { options: eventTypes.value, disabled: true }  
  },
  { dataIndex: "eventWay", title: "执行方式", minWidth: 100, align: 'center',  element: 'select',
    componentProps: { options: eventWays.value, }  
  },
  { dataIndex: "eventDoc", title: "执行内容", minWidth: 100, align: 'center',  element: 'input'},
]

const proceParamsTable = ref()

// 参数设置表格
const paramsCols = [
  { dataIndex: "index", title: "序号", width: 80, align: 'center',  },
  { dataIndex: "paramKey", title: "参数名称", minWidth: 100, align: 'center',  element: 'input'},
  { dataIndex: "paramType", title: "参数类型", minWidth: 100, align: 'center',  element: 'select',
    componentProps: { options: paramTypes.value }  
  },
  { dataIndex: "valueType", title: "参数值类型", minWidth: 100, align: 'center',  element: 'select',
    componentProps: { options: paramTypes.value }  
  },
  { dataIndex: "paramValue", title: "参数值", minWidth: 100, align: 'center',  element: 'input'},
]

onMounted(() => {
  ruleForm.key = props.processId;
  ruleForm.name = props.deployMName;
  proInit();
  getFormOption();
})

function resetBaseInfo() {
  props.bpmElement = window?.bpmnInstances?.bpmElement || {};
}

// 获取未关联业务的表单信息
function getFormOption() {
  dynamiFormApi.getNoLink({ deploymentId: props['deploymentId'] || '' }).then(res => {
    if(res.code == 0) {
      noLinkData.value = res.data || []
      // if(noLinkData.value.length != 0) {
      //   ruleForm.fkdycform = noLinkData.value[0]['modulename'] || ''
      // }
    }
  })
}

// 更新流程的属性xml
function updateBaseInfo(key, value) {
  let element = window.bpmnInstances.elementRegistry.find(el => el.type === "bpmn:Process");
  const attrObj = Object.create(null);
  attrObj[key] = value;
  window.bpmnInstances.modeling.updateProperties(element, attrObj);
}

//加载流程属性
function proInit() {
  window.bpmnInstances = {
    modeler: props.bpmElement,
    modeling: props.bpmElement.get("modeling"),
    moddle: props.bpmElement.get("moddle"),
    eventBus: props.bpmElement.get("eventBus"),
    bpmnFactory: props.bpmElement.get("bpmnFactory"),
    elementFactory: props.bpmElement.get("elementFactory"),
    elementRegistry: props.bpmElement.get("elementRegistry"),
    replace: props.bpmElement.get("replace"),
    selection: props.bpmElement.get("selection")
  };

  ruleForm.sortid = props.properties.sortid;
  ruleForm.titleModel = props.properties.titleModel;
  ruleForm.billmajortype = props.properties.billmajortype;
  ruleForm.billtype = props.properties.billtype;
  if(ruleForm.billmajortype && ruleForm.billtype) {
    ruleForm.billtype1 = `${ruleForm.billmajortype}_BIZ_TYPE_${ruleForm.billtype}`;
  }
  ruleForm.fkdycform = props.properties.fkdycform;
  proceParams.value = props.properties.proceParams;
  eventClass.value = props.properties.eventClass;
  ruleOverDue.value = props.properties.ruleOverDue;
  timedStart.value = props.properties.timedStart;

}

//保存编辑
function saveEdit() {
  let processDefinitionParams= {
    name: ruleForm.name,
    key: ruleForm.key,
    billmajortype: ruleForm.billmajortype,
    billtype: ruleForm.billtype,
    sortid: ruleForm.sortid,
    titleModel: ruleForm.titleModel,
    fkdycform: ruleForm.fkdycform,
    proceParams: proceParams.value,
    ruleOverDue: ruleOverDue.value,
    timedStart: timedStart.value,
    eventClass: eventClass.value
  };

  return processDefinitionParams
}

//添加流程参数行
function addtable() {
  if (proceParams.value == undefined) {
    proceParams.value = new Array();
  }
  let obj = {
    paramKey: '',
    paramType: null,
    paramValue: '',
    valueType:'0',
    keyid: Math.floor(Math.random() * 10000)
  };

  proceParams.value.push(obj);
}

//清空参数列表
function qingchutable() {
  proceParams.value = [];
}

//删除选中的参数
function deltable() {
  if (proceCheckedDetail.value.length == 0) {
    alertC("请先选择要删除的数据");
  } else {
    proceParams.value = proceParams.value.filter(i => !proceCheckedDetail.value.map(o => o.keyid).includes(i.keyid));
  }
}

//动态生成参数列表的index
function rowClassName({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

//选中参数行
function handleDetailSelectionChange(record, selected, selectedRows, nativeEvent) {
  proceCheckedDetail.value = selectedRows;
}

//限制只能输入数字
function formatNumber(field,fieldModel) {
  if(fieldModel=="ruleForm") {
    ruleForm[field] = ruleForm[field].toString().replace(/[^\d]/g, "");
  }
  if(fieldModel=="ruleOverDue") {
    ruleOverDue.value[field] = ruleOverDue.value[field].toString().replace(/[^\d]/g, "");
  }
}

defineExpose({
  saveEdit
})
</script>

<style scoped>

</style>
